package com.partsoft.dits.utils;

import java.util.Locale;

import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.SimpleLocaleContext;
import org.springframework.core.NamedInheritableThreadLocal;
import org.springframework.core.NamedThreadLocal;


/**
 * 区域设置帮助类
 * @author neeker
 *
 */
public abstract class LocaleUtils {
	
	private static final ThreadLocal<LocaleContext> localeContextHolder = new NamedThreadLocal<LocaleContext>("Locale context");

	private static final ThreadLocal<LocaleContext> inheritableLocaleContextHolder =
			new NamedInheritableThreadLocal<LocaleContext>("Locale context");

	/**
	 * 重设当前线程的区域上下文
	 */
	public static void resetLocaleContext() {
		localeContextHolder.set(null);
		inheritableLocaleContextHolder.set(null);
	}
	
	/**
	 * 设置当前区域上下文
	 * @param localeContext
	 */
	public static void setLocaleContext(LocaleContext localeContext) {
		setLocaleContext(localeContext, false);
	}

	/**
	 * 设置当前区域上下文
	 * @param localeContext
	 * @param inheritable 如果为true则使用线程继承方式
	 */
	public static void setLocaleContext(LocaleContext localeContext, boolean inheritable) {
		if (inheritable) {
			inheritableLocaleContextHolder.set(localeContext);
			localeContextHolder.set(null);
		}
		else {
			localeContextHolder.set(localeContext);
			inheritableLocaleContextHolder.set(null);
		}
	}

	/**
	 * 获取区域上下文
	 * @return
	 */
	public static LocaleContext getLocaleContext() {
		LocaleContext localeContext = (LocaleContext) localeContextHolder.get();
		if (localeContext == null) {
			localeContext = (LocaleContext) inheritableLocaleContextHolder.get();
		}
		return localeContext;
	}
	
	public static void setLocale(Locale locale) {
		setLocale(locale, false);
	}

	/**
	 * 设置当前区域,同时设置ZK
	 * @param locale 
	 * @param inheritable 如果是，则使用线程继承方式
	 */
	public static void setLocale(Locale locale, boolean inheritable) {
		LocaleContext localeContext = (locale != null ? new SimpleLocaleContext(locale) : null);
		setLocaleContext(localeContext, inheritable);
	}

	/**
	 * 获取当前区域语言
	 * 同时同步ZK
	 * @return
	 */
	public static Locale getLocale() {
		LocaleContext localeContext = getLocaleContext();
		Locale currentLocale = (localeContext != null ? localeContext.getLocale() : Locale.CHINA);
//		if ( !currentLocale.equals( org.zkoss.util.Locales.getCurrent() ) )
//			org.zkoss.util.Locales.setThreadLocal(currentLocale);
//		
		return currentLocale;
	}
	
	/**
	 * 判断是否当前区域
	 * @param lang 语言代码
	 * @param country 国家代码
	 * @return 如果是当前区域，则返回True
	 */
	public static boolean testCurrent( String lang, String country ) {
		Locale l = getLocale();
		return (lang == null || lang.equals(l.getLanguage())) && (country == null || country.equals(l.getCountry()));
	}
	
}
